package com.helloscala

import scala.collection.mutable

import net.liftweb.common.Loggable
import net.liftweb.http._
import net.liftweb.sitemap.{**, Menu, SiteMap}
import net.liftweb.sitemap.Loc.Stateless

import com.helloscala.web.rest.{DocumentRest, ResourceRest}
import com.helloscala.service.HelloSystem
import com.helloscala.helper.RdbHelpers
import com.helloscala.model.MUser
import com.helloscala.web.{W, HelloURI}

object HelloRules extends Loggable {
  // TODO 改成用具有超时清理的Cache存储
  private lazy val _userIds = mutable.Set[String]() ++ MUser.findAllIds()

  object userIds {
    def contains(v: String): Boolean =
      _userIds.contains(v) match {
        case false if MUser.size(id = Some(v)) > 0L =>
          _userIds += v
          true

        case b =>
          b
      }

    def toList = _userIds.toList
  }

  def init() {
    RdbHelpers.registerSquerylSession()
    LiftRules.addToPackages("com.helloscala.web")
    LiftRules.statelessDispatch.append(ResourceRest)
    LiftRules.statelessDispatch.append(DocumentRest)
    LiftRules.setSiteMap(sitemap)
    LiftRules.statelessRewrite.append(HelloURI.rewrite)

    LiftRules.unloadHooks.append(() => HelloSystem.system.shutdown())
    LiftRules.unloadHooks.append(() => RdbHelpers.close())
  }

  val sitemap = SiteMap(
    Menu("assets") / "assets" / ** >> Stateless,
    Menu("p") / "p" submenus(
      Menu("p-document") / "p" / "document" submenus(
        Menu("p-document-index") / "p" / "document" / "index",
        Menu("p-document-show") / "p" / "document" / "show" >> W.testSiteIdForDocument,
        Menu("p-document-edit") / "p" / "document" / "edit" >> W.testSession >> W.testSiteIdForDocument
        ),
      Menu("p-user") / "p" / "user" submenus(
        Menu("p-user-index") / "p" / "user" / "index",
        Menu("p-user-info") / "p" / "user" / "info",
        Menu("p-user-tag") / "p" / "user" / "tag",
        Menu("p-user-detail") / "p" / "user" / "detail" >> W.testSession,
        Menu("p-user-change_password") / "p" / "user" / "change_password" >> W.testSession
        ),
      Menu("p-tag") / "p" / "tag" / **,
      Menu("p-micro_chat") / "p" / "micro_chat" / **,
      Menu("p-search") / "p" / "search" / **,
      Menu("p-index") / "p" / "index",
      Menu("p-about") / "p" / "about" / **,
      Menu("p-404") / "p" / "404",
      Menu("p-500") / "p" / "500"
      ),
    Menu("demo") / "demo" / **,
    Menu("static") / "static" / **,
    Menu("doc") / "doc" / **,
    Menu("c") / "c" submenus(
      Menu("c-index") / "c" / "index" >> W.testSession,
      Menu("c-sign_in") / "c" / "sign_in",
      Menu("c-sign_up") / "c" / "sign_up" >> W.testSignUp,
      Menu("c-sign_out") / "c" / "sign_out" >> W.signOut,
      Menu("c-forgot_password") / "c" / "forgot_password"
      ),
    Menu("index") / "index",
    Menu("support") / "support" / **
  )

}
